package prd.service.zc.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.teasoft.bee.osql.Condition;
import org.teasoft.bee.osql.Op;
import org.teasoft.bee.osql.OrderType;
import org.teasoft.bee.osql.transaction.Tran;
import org.teasoft.honey.osql.core.ConditionImpl;
import org.teasoft.honey.osql.core.Logger;
import prd.entity.zc.*;
import prd.entity.zc.PrdZcFunds;
import prd.service.zc.PrdFundsService;
import prd.service.zc.PrdI18nService;
import prd.service.zc.PrdPublicMethodService;
import prd.util.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PrdFundsServiceImpl extends BaseServiceImpl<PrdFunds> implements PrdFundsService {

    @Autowired
    PrdPublicMethodService service;

    @Autowired
    PrdI18nService i18nService;

    /**
     * 条件查询
     *
     * @param object
     * @return
     */
    public RespResult queryAll(Map<String, Object> object) {
        try {

            Integer page = Integer.valueOf(object.get("page").toString());//页码
            Integer par_page = Integer.valueOf(object.get("par_page").toString());//条数
            //数据格式：id,ASC;is_show_table,DESC;show_sort,ASC
            String order_by = (String) object.get("order_by");//排序
            String search = JSON.toJSONString(object.get("search"));//查询条件
            Condition condition = replaceSqlJson(search);
            //自定义列加载
            Map<String, Object> map = service.selFieldByTen("prd_funds");
            ResultPage<Object> resultPage = new ResultPage<Object>();

            List<String> list = (List<String>) map.get("myList");//需要展现的字段
            //组装字段
            String str = list.stream().collect(Collectors.joining(","));

            condition.selectField(str);
            int count = count(new PrdFunds(), condition);// 总条数

            condition.start((page - 1) * par_page).size(par_page);
            //数据格式：id,ASC;is_show_table,DESC;show_sort,ASC
            if (!StrUtil.hasBlank(order_by)) {
                String[] split = order_by.split(";");
                for (String strs : split) {
                    String[] order = strs.split(",");
                    condition.orderBy(order[0], (order[1].toLowerCase()).equals("asc") ? OrderType.ASC : OrderType.DESC);
                }
            }
            String selectJson = getSuidRich().selectJson(new PrdFunds(), condition);// 分页查询

            //根据用户有权限的字段进行数据排查
            JSONArray parseArray = JSON.parseArray(selectJson);
            for (int i = 0; parseArray.size() > i; i++) {
                JSONObject jsonObject = parseArray.getJSONObject(i);
                for (String sti : list) {
                    Object object2 = jsonObject.get(sti);
                    if (object2 == null) {//如果为null 可能数据就筛选掉了，手动补上
                        jsonObject.put(sti, null);
                    }
                }
            }

            resultPage.setRowsList(parseArray);
            resultPage.setTotal(count);
            map.put("resultPage", resultPage);

            map.remove("myList");
            return RespResult.success(map);


        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 统计查询
     *
     * @param object
     * @return
     */
    public RespResult countSelect(Map<String, Object> object) {
        Condition condition = service.countSelect(object);
        String selectJson = getSuidRich().selectJson(new PrdFunds(), condition);
        JSONArray parseArray = JSON.parseArray(selectJson);
        return RespResult.success(parseArray);
    }

    /**
     * 根据id查询详情并查出修改所需展示的字段
     *
     * @param id
     * @return
     */
    public RespResult selFundsById(String id) {
//        ResultPage<PrdZcFunds> resultPage = new ResultPage<>();
//        ConditionImpl condition = new ConditionImpl();
//        condition.op("fundid",Op.eq,id);
//        List<PrdZcFunds> select = getSuidRich().select(new PrdZcFunds(), condition);
//        condition.start((page-1)*par_page).size(par_page);
//        List<PrdZcFunds> select1 = getSuidRich().select(new PrdZcFunds(), condition);
//        resultPage.setTotal(select.size());
//        resultPage.setRowsList(select1);
//        return RespResult.success(resultPage);
        Map<String, Object> map = new HashMap<String, Object>();//保存数据，返回到页面
        PrdFunds selectById = getSuidRich().selectById(new PrdFunds(), id);
        map.put("details", selectById);
        map = service.selUpdField("prd_funds", map);
        Object must = map.get("must");
        if (must == null) {
            return RespResult.fail(ResultCode.ERROR.code(), i18nService.queryByIdI18n("CKPZYWQLXG"));
        }
        return RespResult.success(map);
    }


    public RespResult selFundsId(String id, int page, int par_page) {
                ResultPage<PrdZcFunds> resultPage = new ResultPage<>();
        ConditionImpl condition = new ConditionImpl();
        condition.op("fundid",Op.eq,id);
        List<PrdZcFunds> select = getSuidRich().select(new PrdZcFunds(), condition);
        condition.start((page-1)*par_page).size(par_page);
        List<PrdZcFunds> select1 = getSuidRich().select(new PrdZcFunds(), condition);
        resultPage.setTotal(select.size());
        resultPage.setRowsList(select1);
        return RespResult.success(resultPage);
    }

    /**
     * 根据单据号查询详情
     * @param djh
     * @param page
     * @param par_page
     * @return
     */
    public RespResult selFundsByDjh(String djh, int page, int par_page) {
        ResultPage<PrdZcFunds> resultPage = new ResultPage<>();
        ConditionImpl condition = new ConditionImpl();
        condition.op("djh",Op.eq,djh);
        List<PrdZcFunds> select = getSuidRich().select(new PrdZcFunds(), condition);
        condition.start((page-1)*par_page).size(par_page);
        List<PrdZcFunds> select1 = getSuidRich().select(new PrdZcFunds(), condition);
        resultPage.setTotal(select.size());
        resultPage.setRowsList(select1);
        return RespResult.success(resultPage);

    }

    /**
     * 新增经费卡
     *
     * @param prdFunds
     * @return
     */
    @Override
    @Tran
    public RespResult addFunds(PrdFunds prdFunds) {
        //获取登录id
        Object loginId = StpUtil.getLoginId();
        PrdRyk ryk = (PrdRyk) StpUtil.getSessionByLoginId(loginId).get(ResourceUtil.LOCAL_CLINET_USER);//根据id获取用户信息

        try {
            Logger.info("新增开始");
            /*-----判断新增的经费卡是否存在------*/
            String name = prdFunds.getKh();
            Condition condition = new ConditionImpl();
            condition.op("kh", Op.eq, name);
            int count = getSuidRich().count(new PrdFunds(), condition);
            if (count > 0) {
                return RespResult.fail(ResultCode.ERROR.code(), "‘" + name + "’：该卡号已存在；请重新设置！");
            }
            /*-----判断新增的经费卡是否存在------*/

//            prdFunds.setKh(ryk.getKh());
            prdFunds.setYe(prdFunds.getJe());
//            prdFunds.setYe();
//            prdFunds.setJe(ryk.getJe());
//            prdFunds.setDwbh(ryk.getDwbh());
//            prdFunds.setJflx(ryk.getJf);


            prdFunds.setRymc(ryk.getRymc());//创建人
            int add = add(prdFunds);
            Logger.info(add);

            int i = addLog("新增经费卡" + prdFunds, 2, 1, AddressUtils.getLocalIpAddress(), ryk.getRybh(), ryk.getRymc());
            Logger.info(i);

            //绑定经费卡的类型
            String jflx = prdFunds.getJflx();
            String[] values = jflx.split(",");
//            System.out.println(values);

            //循环遍历数组
            for (String value : values) {
                PrdDictionary prdDictionary = new PrdDictionary();
                Condition conditionPrdDictionary = new ConditionImpl();
                conditionPrdDictionary.op("ENUM_CODE", Op.eq, value);
                conditionPrdDictionary.op("DICTIONARY_I18N_EN", Op.eq, "Direction of use");
                List<PrdDictionary> select = getSuidRich().select(prdDictionary, conditionPrdDictionary);

                PrdFundsLx prdFundsLx = new PrdFundsLx();
                List<PrdFunds> select1 = getSuidRich().select(prdFunds, condition);
                prdFundsLx.setFundid(select1.get(0).getId());    //添加经费卡id
                prdFundsLx.setJflx(value);
                prdFundsLx.setJflxmc(select.get(0).getEnum_name());//类型名称
                int insert = getSuidRich().insert(prdFundsLx); //给经费卡绑定类型
                Logger.info(insert);
            }

            //新增经费卡使用单位
            String dwbh = prdFunds.getDwbh();
            String[] val = dwbh.split(",");

            //循环遍历数组
            for (String v : val) {
                PrdDw prdDw = new PrdDw();
                Condition conditionPrdDw = new ConditionImpl();
                conditionPrdDw.op("DWBH", Op.eq, v);
//                conditionPrdDw.op("DICTIONARY_I18N_EN", Op.eq, "Direction of use");
                List<PrdDw> select = getSuidRich().select(prdDw, conditionPrdDw);


                PrdFundsDw prdFundsDw = new PrdFundsDw();
                List<PrdFunds> select1 = getSuidRich().select(prdFunds, condition);
                prdFundsDw.setFundid(select1.get(0).getId());    //添加经费卡id
                prdFundsDw.setDwbh(v);
                prdFundsDw.setDwmc(select.get(0).getDwmc());//单位名称
                int insert = getSuidRich().insert(prdFundsDw);
                Logger.info(insert);
            }

            return RespResult.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 修改经费卡
     *
     * @param prdFunds
     * @return
     */
    @Override
    @Tran
    public RespResult updateByIdFunds(PrdFunds prdFunds) {
        //获取登录id
        Object loginId = StpUtil.getLoginId();
        PrdRyk ryk = (PrdRyk) StpUtil.getSessionByLoginId(loginId).get(ResourceUtil.LOCAL_CLINET_USER);//根据id获取用户信息

        try {
            Integer id = prdFunds.getId();
            int update = update(prdFunds);
            Logger.info(update);

            //根据卡号删除经费卡类型
            PrdFundsLx prdFundsLx = new PrdFundsLx();
            Integer fundid = prdFunds.getId();
            Condition condition = new ConditionImpl();
            condition.op("FUNDID", Op.eq, fundid);


            int delete = getSuidRich().delete(prdFundsLx, condition);

            //绑定经费卡的类型
            String jflx = prdFunds.getJflx();
            String[] values = jflx.split(",");
//            System.out.println(values);

            //绑定经费卡的类型
            String name = prdFunds.getKh();
            Condition condition2 = new ConditionImpl();
            condition2.op("kh", Op.eq, name);

            List<PrdFunds> select1 = getSuidRich().select(prdFunds, condition2);
            //循环遍历数组
            for (String value : values) {
                PrdDictionary prdDictionary = new PrdDictionary();
                Condition conditionPrdDictionary = new ConditionImpl();
                conditionPrdDictionary.op("ENUM_CODE", Op.eq, value);
                conditionPrdDictionary.op("DICTIONARY_I18N_EN", Op.eq, "Direction of use");
                List<PrdDictionary> select = getSuidRich().select(prdDictionary, conditionPrdDictionary);

//                PrdFundsLx prdFundsLx = new PrdFundsLx();

//            PrdFundsLx prdFundsLx = new PrdFundsLx();

                prdFundsLx.setFundid(select1.get(0).getId());    //添加经费卡id
                prdFundsLx.setJflx(value);
                prdFundsLx.setJflxmc(select.get(0).getEnum_name());//类型名称
                int insert = getSuidRich().insert(prdFundsLx); //给经费卡绑定类型
                Logger.info(insert);
            }

            //1.删除经费卡单位
            PrdFundsDw prdFundsDw = new PrdFundsDw();
//            Integer fundidByDw = prdFunds.getId();
            Condition conditionByDw = new ConditionImpl();
            conditionByDw.op("FUNDID", Op.eq, fundid);

            int delete1 = getSuidRich().delete(prdFundsDw, conditionByDw);

            //新增经费卡使用单位
            String dwbh = prdFunds.getDwbh();
            String[] val = dwbh.split(",");

            //循环遍历数组,添加绑定的单位
            for (String v : val) {
                PrdDw prdDw = new PrdDw();
                Condition conditionPrdDw = new ConditionImpl();
                conditionPrdDw.op("DWBH", Op.eq, v);
//                conditionPrdDw.op("DICTIONARY_I18N_EN", Op.eq, "Direction of use");
                List<PrdDw> select = getSuidRich().select(prdDw, conditionPrdDw);

//                PrdFundsDw prdFundsDw = new PrdFundsDw();
//                List<PrdFunds> select1 = getSuidRich().select(prdFunds, conditionByDw);
                prdFundsDw.setFundid(select1.get(0).getId());    //添加经费卡id
                prdFundsDw.setDwbh(v);
                prdFundsDw.setDwmc(select.get(0).getDwmc());   //单位名称
                int insert = getSuidRich().insert(prdFundsDw);
                Logger.info(insert);
            }



            int i = addLog("根据" + id + "修改经费卡" + prdFunds, 3, 1, AddressUtils.getLocalIpAddress(), ryk.getRybh(),
                    ryk.getRymc());
            Logger.info(i);
            return RespResult.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 删除经费卡
     *
     * @param prdFunds
     * @param ids
     * @return
     */
    @Override
    @Tran
    public RespResult deleteFunds(PrdFunds prdFunds, String ids) {
        //获取登录id
        Object loginId = StpUtil.getLoginId();
        PrdRyk ryk = (PrdRyk) StpUtil.getSessionByLoginId(loginId).get(ResourceUtil.LOCAL_CLINET_USER);//根据id获取用户信息

        try {
            //1.删除关联的经费卡类型表
            PrdFundsLx prdFundsLx = new PrdFundsLx();
            Condition condition = new ConditionImpl();
            condition.op("FUNDID", Op.eq, ids);
            getSuidRich().delete(prdFundsLx, condition);

            //2.删除关联的经费卡单位表
            PrdFundsDw prdFundsDw = new PrdFundsDw();
            getSuidRich().delete(prdFundsDw,condition);

            Logger.info("删除开始，根据id：" + ids + "进行删除");
            int i = deleteById(prdFunds.getClass(), ids);
            Logger.info(i);
            int log = addLog("根据" + ids + "删除经费卡", 4, 1, AddressUtils.getLocalIpAddress(), ryk.getRybh(),
                    ryk.getRymc());
            Logger.info(log);
            return RespResult.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
